package main

import (
	"Dataform"
	"Logger"
	"encoding/json"
	"net"
	"os"
)

var serverList Dataform.ServerInfos

func setLogger() {
	Logger.SetConsole(true)
	Logger.SetRollingDaily("../logs", "Manager-logs.txt")
}

func readConfigFile() {
	serverConfig, err := os.Open("../serverconfigs.conf")
	checkError(err, true)
	defer serverConfig.Close()
	buffer := make([]byte, 2048)
	length, err := serverConfig.Read(buffer)
	checkError(err, true)
	err = json.Unmarshal(buffer[:length], &serverList)
	checkError(err, true)

	Logger.Info("Config file read success...setting up server...")
}

func findServerInfo(index int, tp int) Dataform.ServerInfo {
	var t int
	t = 0
	for i := 0; i < len(serverList.Info); i++ {
		if serverList.Info[i].Type == tp {
			t++
			if t == index {
				break
			}
		}
	}
	return serverList.Info[t]
}

func initServers() {
	var connectorAmount,
		gateAmount,
		logicAmount int

	var port string
	var onlineServerAmount int

	for i := 0; i < len(serverList.Info); i++ {
		if serverList.Info[i].Type == Dataform.MANAGER {
			port = serverList.Info[i].Port
			break
		}
	}
	listener, err := net.Listen("tcp", ":"+port)
	checkError(err, true)

	infoBuffer := make([]byte, 128)
	for {
		if onlineServerAmount == len(serverList.Info)-1 {
			listener.Close()
			Logger.Info("All servers are online")
			break
		}
		client, err := listener.Accept()
		checkError(err, false)

		onlineServerAmount = onlineServerAmount + 1

		length, err := client.Read(infoBuffer)
		switch string(infoBuffer[:length]) {
		case "CONNECTOR":
			{
				buffer, err := json.Marshal(findServerInfo(connectorAmount, Dataform.CONNECTOR))
				connectorAmount = connectorAmount + 1
				checkError(err, false)
				client.Write(buffer)
				client.Close()
				Logger.Info("New Connector")
			}
		case "GATE":
			{
				buffer, err := json.Marshal(findServerInfo(gateAmount, Dataform.GATE))
				gateAmount = gateAmount + 1
				checkError(err, false)
				client.Write(buffer)
				client.Close()
				Logger.Info("New Gate")
			}
		case "LOGIC":
			{
				buffer, err := json.Marshal(findServerInfo(logicAmount, Dataform.LOGIC))
				logicAmount = logicAmount + 1
				checkError(err, false)
				client.Write(buffer)
				client.Close()
				Logger.Info("New Logic")
			}
		}
	}
}

func main() {
	setLogger()
	readConfigFile()
	initServers()
}

func checkError(e error, crash bool) bool {
	if e != nil {
		Logger.Error(e.Error())
		if crash {
			os.Exit(444)
		}
		return false
	}
	return true
}
